﻿namespace UITest.Helpers
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.Linq;
    using System.Threading;

    /// <summary>
    ///     The process helper.
    /// </summary>
    public class ProcessHelper
    {
        #region Public Methods and Operators

        /// <summary>
        /// The assert that.
        /// </summary>
        /// <param name="istrue">
        /// The istrue.
        /// </param>
        /// <param name="message">
        /// The message.
        /// </param>
        /// <param name="repeat">
        /// The repeat.
        /// </param>
        /// <param name="wait">
        /// The wait.
        /// </param>
        /// <exception cref="ArgumentException">
        /// </exception>
        /// <exception cref="TimeoutException">
        /// </exception>
        public void AssertThat(Func<bool> istrue, string message, int repeat = 3, int wait = 20)
        {
            if (repeat < 1)
            {
                throw new ArgumentException(string.Format("repeat must be greather than 0 (actual:{0})", repeat));
            }

            for (int i = 0; i < repeat; i++)
            {
                if (istrue.Invoke())
                {
                    return;
                }

                Thread.Sleep(wait * 1000);
            }

            throw new TimeoutException(message);
        }

        /// <summary>
        /// The kill process.
        /// </summary>
        /// <param name="processName">
        /// The process name.
        /// </param>
        public virtual void KillProcess(string processName)
        {
            IEnumerable<Process> processes = Process.GetProcesses().Where(x => x.ProcessName == processName);

            foreach (Process process in processes)
            {
                try
                {
                    if (!process.HasExited)
                    {
                        process.Kill();
                    }
                }
                catch (Exception)
                {
                }
            }
        }

        #endregion
    }
}